const express = require("express");
const fs = require("fs");
const app = express();
const history = require("connect-history-api-fallback");
app.use(history());
app.use(express.static("../dist"));
const { createProxyMiddleware } = require("http-proxy-middleware");
function getNetWorkIp() {
  let needHost = "";
  try {
    let network = os.networkInterfaces();
    for (const dev in network) {
      let iface = network[dev];
      for (let i = 0; i < iface.length; i++) {
        const alias = iface[i];
        if (
          alias.family === "IPv4" &&
          alias.address !== "127.0.0.1" &&
          !alias.internal
        ) {
          needHost = alias.address;
        }
      }
    }
  } catch (error) {
    needHost = "localhost";
  }
  return needHost;
}
const IP = getNetWorkIp();
console.log("Ip", IP);
const port = 9001;
app.use(
  "/api/",
  createProxyMiddleware({
    target: "http://imapi2.aic3ruchech6ua5.com:80",
    changeOrigin: true,
    pathRewrite: {
      "^/api/": "/",
    },
  })
);
app.use(
  "/maps/api/",
  createProxyMiddleware({
    target: "https://maps.googleapis.com",
    changeOrigin: true,
    pathRewrite: {
      "^/maps/api/": "/maps/api/",
    },
  })
);
app.get("/", (req, res) => {
  fs.readFile("../dist/index.html", "utf-8", (err, content) => {
    if (err) {
      console.log('We cannot open "index.html" file.');
    }
    res.writeHead(200, {
      "Content-Type": "text/html; charset=utf-8",
    });
    res.end(content);
  });
});
console.log(`start: http://localhost:${port}`);
app.listen(port);
